package com.itfenghuang.util;

import com.itfenghuang.domain.User;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

//导出报表类
public class ExportUser {
    //返回响应
    public String exportUser(List<User> list, HttpServletResponse response) throws Exception {

        response.setCharacterEncoding("UTF-8");
        //1.创建excel文件
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //2.创建sheet页,一个表格
        HSSFSheet sheet = hssfWorkbook.createSheet("用户信息表");
        //3.创建标题行
        HSSFRow row = sheet.createRow(0);
        //4.字段名
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("账号");
        row.createCell(2).setCellValue("密码");
        row.createCell(3).setCellValue("电话");
        row.createCell(4).setCellValue("性别");
        row.createCell(5).setCellValue("名字");
        row.createCell(6).setCellValue("生日");
        row.createCell(7).setCellValue("余额");
        //5.遍历将数据放到excel中
        for (User user : list) {
            HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1);
            row1.createCell(0).setCellValue(user.getId());
            row1.createCell(1).setCellValue(user.getUsername());
            row1.createCell(2).setCellValue(user.getPassword());
            row1.createCell(3).setCellValue(user.getPhone());
            row1.createCell(4).setCellValue(user.getGender());
            row1.createCell(5).setCellValue(user.getRealname());
            row1.createCell(6).setCellValue(user.getBirthday());
            row1.createCell(7).setCellValue(user.getMoney());
        }
        //6.设置下载时客户端excel的名字
        response.setContentType("application/x-xls;charset=utf-8");//固定的形式
        //7.Content-Disposition中指定额类型扩展名,
        //并且弹出下载对话框中的文件类型是按照扩展名显示的
        //保存后按照下面的命名显示
        response.setHeader("Content-Disposition",
            "attachment;filename="+new String("用户表".getBytes(),
                    "iso-8859-1")+".xls");
        //8.输出字节流
        ServletOutputStream outputStream = response.getOutputStream();
        hssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        return outputStream.toString();
    }
}
